/**
 * Copyright 2007-2008 Alex Tkachman
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ait.actors;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.Callable;

public abstract class Task implements Callable {
    public final static int STOPPED = 0;
    public final static int INQUEUE = 1;  // in ownQueue
    public final static int RUNNING = 2;  // working
    public final static int WAITING = 3;  // waiting

    private volatile int status;
    private volatile Thread ownerThread;

    private final static AtomicIntegerFieldUpdater<Task> statusUpdater = AtomicIntegerFieldUpdater.newUpdater(Task.class, "status");
    private final static AtomicReferenceFieldUpdater<Task,Thread> ownerUpdater = AtomicReferenceFieldUpdater.newUpdater(Task.class, Thread.class, "ownerThread");

    private static final RuntimeException STOPED = new RuntimeException();

    public Task() {
    }

    /**
     * Scheduling this actor for execution
     */
    public void start () {
        if(!ownerUpdater.compareAndSet(this, null, null)) {
            throw new IllegalStateException();
        }
        ensureStatus(STOPPED,INQUEUE);
//        Scheduler.schedule (this);
    }

    /**
     * Stopping actor
     */
    public void stop () {
        if (ownerUpdater.compareAndSet(this, Thread.currentThread(), null)) {
            ensureStatus(RUNNING, STOPPED);
            throw STOPED;
        }
        else {
            if(ownerUpdater.compareAndSet(this, null, null)) {
                ensureStatus(STOPPED, STOPPED);
            }
            else {
                // can't stop actor running in another thread
                throw new IllegalStateException();
            }
        }
    }

    private void ensureStatus(int expected, int value) {
        if (!statusUpdater.compareAndSet(this, expected, value))
          throw new IllegalStateException("Illegal state. Expected: " + expected + " actual: " + status);
    }

    public final Object call() throws Exception {
        final Thread currentThread = Thread.currentThread();
        try {
            if(!ownerUpdater.compareAndSet(this, null, currentThread))
              throw new IllegalStateException();

            ensureStatus(INQUEUE, RUNNING);
            return calculate ();
        }
        catch (Throwable t) {
            t.printStackTrace();
            throw new RuntimeException(t);
        }
        finally {
            if (!statusUpdater.compareAndSet(this, RUNNING, STOPPED)) {
                // act () changed status of this actor, so we should trust this change
            }
            else {
                ownerThread = null;
            }
        }
    }

    public final void execute () {
        final Thread currentThread = Thread.currentThread();
        if (currentThread instanceof WorkerThread) {
            WorkerThread thread = (WorkerThread) currentThread;
            start ();
            while (status != STOPPED) {
                thread.workerStep();
            }
        }
        else {
            new ParkExecuteAndUnparkTask(this, currentThread).start();
        }
    }

    protected abstract Object calculate() throws Exception;

    public int getStatus() {
        return status;
    }

    public Thread getOwnerThread() {
        return ownerThread;
    }

    public static Task actor (final Callable delegate) {
        return new RunnableTask(delegate);
    }

    private static class RunnableTask extends Task {
        protected final Callable delegate;

        public RunnableTask(Callable delegate) {
            this.delegate = delegate;
            start ();
        }

        protected Object calculate() throws Exception {
            return delegate.call();
        }
    }

    private static class DelegatingTask extends Task {
        protected final Task delegate;

        public DelegatingTask(Task delegate) {
            this.delegate = delegate;
        }

        protected Object calculate() throws Exception {
            return delegate.call();
        }
    }

    private static class ParkExecuteAndUnparkTask extends DelegatingTask {
        private final Thread thread;

        // 0 - initial
        // 1 - started
        // 2 - plan to park
        // 3 - completed
        private volatile int lock;

        private final static AtomicIntegerFieldUpdater updateLock = AtomicIntegerFieldUpdater.newUpdater(ParkExecuteAndUnparkTask.class, "lock");

        public ParkExecuteAndUnparkTask(Task task, Thread thread) {
            super(task);
            this.thread = thread;
        }

        public void start() {
            super.start();
            if (!updateLock.compareAndSet(this, 0, 1))
              throw new IllegalStateException();

            if (updateLock.compareAndSet(this, 1, 2))
              LockSupport.park();
        }

        protected Object calculate() throws Exception {
            try {
                return super.calculate();
            }
            finally {
                if (updateLock.compareAndSet(this, 2, 3))
                  LockSupport.unpark(thread);
            }
        }
    }
}
